//
//  BHImageVideoPicker.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/6.
//

import UIKit

protocol BHImageVideoPickerDelegate {
    func responseImageChose(imageArray: [BHImageOrVideoModel])
    func didCameraTakeImage(image: BHImageOrVideoModel?)
    func didChoseVideo(video: BHImageOrVideoModel?)
    func didChoseArrayNotNull(count: Int)
}


class BHImageVideoPicker: UIView {
    var delegate: BHImageVideoPickerDelegate?
    
    
    lazy var collectionView: UICollectionView = {
        let flowlayout = UICollectionViewFlowLayout.init()
        let view = UICollectionView.buildCollectionView(layout: flowlayout)
        view.backgroundColor = .white
        view.register(UINib.init(nibName: "BHImageOrVideoItemCell", bundle: nil), forCellWithReuseIdentifier: "BHImageOrVideoItemCell")
        view.regiseterNib(nibName: "BHImageTakeCollectionViewCell")
        view.delegate = self
        view.dataSource = self
        
        return view
    }()
    
    var type: Int = 0
    var allowTakeImage: Bool = true
    var allowMutableChose: Bool = true
    var maxCount: Int = 9
    var loadType: Int = 0 {
        didSet {
            if self.addArray.count != 0 {
                self.addArray.removeAll()
            }
            BHImagePickManager.permissionForAlbum { (status) in
                if status == .authorized {
                    if self.loadType == 0 {
                        BHMediaTool.sourceFromAlbum(type: .image, videoMaxTime: 0) { (array) in
                            self.sourceArray = array
                        }
                    }else {
                        BHMediaTool.sourceFromAlbum(type: .video, videoMaxTime: 30) { (array) in
                            self.sourceArray = array
                        }
                    }
                }
            }
            
        }
    }
    
    var sourceArray: [BHImageOrVideoModel] = [] {
        didSet {
            if self.addArray.count != 0 {
                for choseModel in self.addArray {
                    for model in sourceArray {
                        if choseModel.asset == model.asset {
                            model.index = choseModel.index
                            break
                        }
                    }
                }
            }
            self.collectionView.reloadData()
            
        }
    }
    
    var addArray: [BHImageOrVideoModel] = []
    var choseVideo: BHImageOrVideoModel?
    
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(self.collectionView)
        self.collectionView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height);
        
    }
    
    func choseCompleteCall() {
        if self.addArray.count != 0 {
            self.delegate?.responseImageChose(imageArray: self.addArray)
        }
        if self.choseVideo != nil {
            self.delegate?.didChoseVideo(video: self.choseVideo)
        }
    }
   
}

extension BHImageVideoPicker: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.loadType == 0 {
            if self.allowTakeImage == true {
                return self.sourceArray.count+1
            }else {
                return self.sourceArray.count
            }
        }else {
            return self.sourceArray.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if self.type == 0 {
            let halfW = (UIScreen.width-40)/3.0
            return  CGSize(width: halfW-0.5, height: halfW-0.5)
        }else {
            return CGSize(width: UIScreen.width, height: UIScreen.height)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if self.type == 0 {
            return UIEdgeInsets(top: 0, left: 16, bottom: 20, right: 16)
        }else {
            return .zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        if self.type == 0 {
            return 4
        }else {
            return 0
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        if self.type == 0 {
            return 4
        }else {
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.loadType == 0 && self.allowTakeImage == true{
            if indexPath.row == 0 {
                BHCommonTool.init().takePhoto { (img) in
                    if img != nil {
                        let model: BHImageOrVideoModel = BHImageOrVideoModel.init()
                        model.index = 1
                        model.takeImage = img
                        self.delegate?.didCameraTakeImage(image: model)
                    }
                }
                return
            }
        }
        if self.loadType == 0 {
            BHMediaTool.showPreview(array: self.sourceArray, current: indexPath.row-1)
        }else { // 视频选择
            let model = self.sourceArray[indexPath.row]
            BHMediaTool.previewVideo(model: model)
        }
    }
}

extension BHImageVideoPicker {
    func begainOperation(indexPath: IndexPath) {
        if self.allowTakeImage == true && self.loadType == 0{
            let model = self.sourceArray[indexPath.row - 1]
            if self.addArray.contains(model) { // 此时为去除
                self.removeImage(model: model)
            }else {
                self.addImage(model: model)
            }
        }else {
            let model = self.sourceArray[indexPath.row]
            if self.loadType == 1 { // 视频
                if model.index == 1 {
                    model.index = 0
                    self.choseVideo = nil
                    self.delegate?.didChoseArrayNotNull(count: 0)
                }else {
                    if self.choseVideo != nil {
                        BHToast.toast(text: "只能选择一个视频文件")
                        return
                    }
                    model.index = 1
                    self.choseVideo = model
                    
                    self.delegate?.didChoseArrayNotNull(count: 1)
                }
                self.collectionView.reloadData()
                
            }else {
                if self.addArray.contains(model) { // 此时为去除
                    self.removeImage(model: model)
                }else {
                    self.addImage(model: model)
                }
            }
        }
    }
    
    
    func resortAdd(model: BHImageOrVideoModel) {
        for containModel in self.addArray {
            if containModel.index > model.index {
                containModel.index = containModel.index-1
            }
        }
        model.index = 0
        self.collectionView.reloadData()
        self.delegate?.didChoseArrayNotNull(count: self.addArray.count)
    }
    
    func removeImage(model: BHImageOrVideoModel) {
        self.addArray.remove(at: model.index-1)
        self.resortAdd(model: model)
    }
    
    func addImage(model: BHImageOrVideoModel) {
        if self.allowMutableChose == false { // 单选
            if self.addArray.count != 0 {
                self.addArray.removeAll()
            }
            self.addArray.append(model)
            self.delegate?.responseImageChose(imageArray: self.addArray)
            return
        }
        
        if self.addArray.count >= self.maxCount {
            BHToast.toast(text: "最多选择\(self.maxCount)张图片")
            return
        }
        
        model.index = self.addArray.count+1
        self.addArray.append(model)
        collectionView.reloadData()
        
        self.delegate?.didChoseArrayNotNull(count: self.addArray.count)
    }
}

extension BHImageVideoPicker: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if self.allowTakeImage == true && self.loadType == 0 {
            
            if indexPath.row == 0 {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHImageTakeCollectionViewCell", for: indexPath) as! BHImageTakeCollectionViewCell
                return cell
            }else {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHImageOrVideoItemCell", for: indexPath) as! BHImageOrVideoItemCell
                cell.type = self.type
                let model = self.sourceArray[indexPath.row - 1]
                cell.model = model
                cell.addOrClearImageActBlock = { [weak self] in
                    self?.begainOperation(indexPath: indexPath)
                }
                cell.choseSignBtn.isHidden = false
                return cell
            }
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHImageOrVideoItemCell", for: indexPath) as! BHImageOrVideoItemCell
            cell.type = self.type
            let model = self.sourceArray[indexPath.row]
            cell.model = model
            cell.addOrClearImageActBlock = { [weak self] in
                self?.begainOperation(indexPath: indexPath)
            }
            cell.choseSignBtn.isHidden = false
            return cell
        }
    }
    
}
